﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Threading;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace scancode
{
    public partial class Form1 : Form
    {

        
        
        //public static String maxId = "0";
        public static OleDbConnection conn;
        public static String code;
        public static String url;

        public Form1()
        {
            InitializeComponent();
            this.textBox2.Text = Read("url.ini");
            url = this.textBox2.Text;
            Thread thread = new Thread(sendReadCard);
            thread.Start(); 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            

        }

       

        private void button2_Click(object sender, EventArgs e)
        {
            

        }

        private void box1(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                if (Regex.IsMatch(this.textBox1.Text, "[JN]-\\d{2}-\\d{6}") && this.comboBox1.Text != "" && this.textBox1.Text.ToString().Length == 12)
                {
                    try
                    {
                        if (conn == null)
                        {
                            initdb();
                        }
                        string Insert = "insert into tblReadCard(barCode,readDate,readTime,hallDoorId,pcName,portId,inOut)values('" + this.textBox1.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" + this.comboBox1.Text + "'," + "0,0,0)";
                        OleDbCommand cmd = new OleDbCommand(Insert, conn);//执行命令
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        code = this.textBox1.Text;
                        this.textBox1.Text = "";
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message + "33");
                    }
                }
                else {
                    this.textBox1.Text = "";
                }
            }


        }



        public void initdb()
        {
            try
            {
                //改为正式环境中本地数据库nocdoor.mdb文件的位置路径
                conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=nocdoor.mdb");
                conn.Open();
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message+"1");
            }
        }

        public void sendReadCard()
        {
            while (true)
            {

                if (conn == null)
                {
                    initdb();
                }
                String maxId = Read("maxid.ini");
                string sql = "select * from tblReadCard where readID > " + maxId + " order by readID asc";
                OleDbCommand cmd = new OleDbCommand(sql, conn);
                try
                {
                    OleDbDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        String readId = reader[0].ToString();
                        String barCode = (String)reader.GetValue(1);
                        String readDate = (String)reader.GetValue(2);
                        String readTime = (String)reader.GetValue(3);
                        String pcName = "";
                        String portId = "";
                        String inOut = "";
                        String hallDoorId = reader[7].ToString();
                        String result = "readId=" + readId + "&barCode=" + barCode + "&readDate=" + readDate + "&readTime=" + readTime
                            + "&pcName=" + pcName + "&portId=" + portId + "&inOut=" + inOut + "&hallDoorId=" + hallDoorId;
                        //此地址改为正式服务器地址
                        Boolean f = HttpGet(url, result);
                        if (f)
                        {
                            write("maxid.ini", readId);
                        }
                        //休眠一下再传
                        Thread.Sleep(10);
                    }
                    if (!reader.IsClosed)
                    {
                        reader.Close();
                        cmd.Dispose();
                        conn.Close();
                    }
                }
                catch (Exception e)
                {
                    //throw;
                    //MessageBox.Show(e.Message+"2");
                }

                try
                {
                    //休眠一下再传
                    Thread.Sleep(3000);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }


        public static String Read(String file)
        {
            //String file = "maxid.ini";
            if (!File.Exists(file))
            {
                // 创建文件
                FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs); // 创建写入流
                sw.WriteLine("0"); // 写入Hello World
                sw.Close(); //关闭文件
                return "0";
            }
            else
            {
                StreamReader sr = new StreamReader(file, Encoding.Default);
                String maxId = "";
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    maxId += line.ToString();
                }
                sr.Close();
                return maxId.Trim();
            }
        }

        public static void write(String file, String content)
        {
            //String file = "maxid.ini";
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(content); // 写入
            sw.Close(); //关闭文件
        }


        public static Boolean HttpGet(string Url, string postDataStr)
        {
            Boolean flag = false;
            string retString = "";
            try
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                flag = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return flag;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //this.TopMost = true;     //设置窗体为最前端显示
            //this.WindowState = FormWindowState.Maximized;    //最大化窗体 
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            this.label4.Text = code + "入场";
        }

        private void box1Enter(object sender, EventArgs e)
        {
            /*if (this.textBox1.Text != "" && this.comboBox1.Text != "")
            {
                try
                {
                    string Insert = "insert into tblReadCard(barCode,readDate,readTime,hallDoorId,pcName,portId,inOut)values('" + this.textBox1.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" + this.comboBox1.Text + "'," + "0,0,0)";
                    OleDbCommand cmd = new OleDbCommand(Insert, conn);//执行命令
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    code = this.textBox1.Text;
                    this.textBox1.Text = "";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "3");
                }
            }*/

            if (Regex.IsMatch(this.textBox1.Text, "[JN]-\\d{2}-\\d{6}") && this.comboBox1.Text != "" && this.textBox1.Text.ToString().Length == 12)
            {
                try
                {
                    if (conn == null)
                    {
                        initdb();
                    }
                    string Insert = "insert into tblReadCard(barCode,readDate,readTime,hallDoorId,pcName,portId,inOut)values('" + this.textBox1.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" + this.comboBox1.Text + "'," + "0,0,0)";
                    OleDbCommand cmd = new OleDbCommand(Insert, conn);//执行命令
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    code = this.textBox1.Text;
                    this.textBox1.Text = "";
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message + "34");
                }
            }
            else
            {
                this.textBox1.Text = "";
            }
        }

        private void box2Changed(object sender, EventArgs e)
        {
            url = this.textBox2.Text;
        }

        private void textBox2_Leave(object sender, EventArgs e)
        {
            write("url.ini", this.textBox2.Text);
        }
    }
}
